% Function : Gray Correlation Analysis
% Parameter:
%   dst: reference sequence and each column is time series of one channel(matrix)
%   src: factor sequence and each column is time series of one channel(matrix)
% Return:
%   r: correlation degree matrix(each row is correlation between one reference and all factors)
%   o: descending order of correlation degree(row corresponds to row in r above)
function [r, o] = GrayCorrelation(dst, src)
    % Step 1: dimensionless process(normalization)
    dst = min_max(dst);
    src = min_max(src);

    % Step 2: correlation coefficient(xi)
    [m1, n1] = size(dst);
    [m2, n2] = size(src);

    if m1 ~= m2
        disp('number of row is not consistent');
    end

    % preallocation
    r = zeros(n1, n2);  % relation matrix
    o = zeros(n1, n2);  % ascending order matrix

    for i = 1 : n1
        % matrix of difference
        tmp = dst(:, i) - src;

        tmp = abs(tmp);

        mmin = min(min(tmp));
        mmax = max(max(tmp));

        % resolution
        rho = 0.5;

        % coefficient
        xi = (mmin + rho * mmax) ./ (tmp + rho * mmax);

        % Step 3: correlation degree(r)
        k       = size(xi, 1);
        r(i, :) = sum(xi) / k;

        % Step 4: sort and save rank(insertion sort)
        o(i, :) = SortedIndex(r(i, :));
    end
end

% SubFunction %
function data = min_max(data)
    minx = min(data);
    maxx = max(data);
    difx = maxx - minx;

    data = (data - minx) ./ difx;
end
